import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Card, Button, message, Table
} from 'antd';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import { filterAuth } from "@/support/common";
import PropTypes from "prop-types";
import styles from '../../../components/common/PateoTable/TableList.less';
import { PlusOutlined } from '@ant-design/icons';
import router from 'umi/router';
import * as XLSX from 'xlsx';

const mapStateToProps = (state: any) => ({
  collectionGroup: state.collectionGroup,
  loading: state.loading.effects['collectionGroup/getFetchPage'],
});
let pageObj = {};
class collectionGroup extends PureComponent<any, any> {

  static contextTypes = {
    permissions: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      pageParams: {
        pageNo: 1,
        pageSize: 10,
      },
    };
  }

  componentDidMount() {
    this.handleFreshPage();
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'collectionGroup/initData'
    });
  }
  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues, pageParams } = this.state;
    dispatch({
      type: 'collectionGroup/getFetchPage',
      payload: { url: '/data/collection/vehicle/list', ...formValues, ...pageParams, },
    });
  };

  handleAdd = () => {
    router.push('/connectPlat/collectionGroup/addCollectionGroup');
  }
 
 
  handleEdit = (record:any) => { //isConfig：0-默认，1-被配置
    if(record.isConfig === 1){
      message.warning("该采集车辆组已被使用，无法编辑");
    }else{
    sessionStorage.setItem('groupInfo', JSON.stringify(record));
    router.push('/connectPlat/collectionGroup/editCollectionGroup');
    }
  }

  closeEditModal = () => {
   
  }
  handleDetail = (record:any) => {
    sessionStorage.setItem('groupInfo', JSON.stringify(record));
    router.push('/connectPlat/collectionGroup/detailCollectionGroup');
  }

  closeDetailModal = () => {
  
  }

  handleDelete = (id: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'collectionGroup/getData',
      payload: { url: `/data/collection/vehicle/delete/${id}`},
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('删除成功');
          dispatch({
            type: "collectionGroup/getFetchPage",
            payload: { url: "/data/collection/vehicle/list" }
          });
        }
      },
    });
  };

  handleImport = (record: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'collectionGroup/getData',
      payload: { url: `/data/collection/vehicle/export/${record.id}`},
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('导出采集车辆组成功');
          const data: any = [];
          response.data.forEach((e, i) => {
            data.push({
              index: i + 1,
              vin: e.vin,
              brandName: e.brandName,
              seriesName: e.seriesName,
              typeName: e.typeName,
              mark: e.mark,
            });
          });
          const header = {
            index: '序号',
            vin: 'VIN码',
            brandName: '品牌',
            seriesName: '车系',
            typeName: '车型',
            mark: '备注',
          };
          const ws = XLSX.utils.json_to_sheet([header, ...data], { skipHeader: true });
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, 'export');
          XLSX.writeFile(wb, 'export.xlsx');
        }
      },
    });
    };
    handleFormReset = () => {
      this.searchForm?.current.setFieldsValue({});
      this.setState({
        formValues: {},
        pageParams: {
          pageNo: 1,
          pageSize: 10,
        },
      });
    };
    // 分页时触发
    tableOnChange = (pagination: any) => {
      const current = pagination.current;
      this.setState(
        {
          pageParams: {
            pageNo: current,
            pageSize: pagination.pageSize,
          },
        },
        () => {
          this.handleFreshPage();
        },
      );
    };
    handleFreshPage = () => {
      const { dispatch } = this.props;
      const { formValues, pageParams } = this.state;
      dispatch({
        type: 'collectionGroup/getFetchPage',
        payload: {
          url: '/data/collection/vehicle/list',
          ...formValues,
          ...pageParams,
        },
      });
    };
  render() {
    const { collectionGroup: { pageData: { list, pagination } }, loading, location: { pathname = '/' } } = this.props;
    pageObj = pagination;
    const { formValues,} = this.state;
    const columns = [
      {
        title: '采集车辆组名称',
        dataIndex: 'vehicleGroupName'
      },
      {
        title: '采集车辆数（台）',
        dataIndex: 'collectNumber'
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 230,
        render: (text: any, record: any) => {
          const btns = [];
          const exportBtn = {
            title: '导出车辆',
            key: 'export',
            auth: "collectionGroup_export",
            onConfirm: () => this.handleImport(record),
        };
          const editBtn = {
            title: '编辑',
            key: 'edit',
            auth: "collectionGroup_edit",
            onConfirm: () => this.handleEdit(record),
        };
          const detailBtn = {
            title: '查看',
            key: 'show',
            auth: "collectionGroup_show",
            onConfirm: () => this.handleDetail(record),
          };
        const deleteBtn = {
          title: '删除',
          key: 'delete',
          auth: "collectionGroup_delete",
          message: '确认删除吗？',
          Popconfirm: true,
          onConfirm: () => this.handleDelete(record.id),
       };
        btns.push(exportBtn,editBtn,detailBtn,deleteBtn)
          return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const searchItems = [
      {
        type: 'input',
        title: '采集车辆组名称',
        key: 'vehicleGroupName',
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{ type: 'collectionGroup/getFetchPage', url: '/data/collection/vehicle/list' }}
            saveFormValues={(val: any) => this.setState({ formValues: Object.assign(formValues, val) })}
            handleFormReset={this.handleFormReset}
          />
        </Card>
        <Card className={styles.standardTable}>
          {
            filterAuth("collectionGroup_toAdd", this.context.permissions, pathname) ? (
              <div className="my_newItem">
                <Button
                  size="small"
                  icon={<PlusOutlined />}
                  type="primary"
                  onClick={() => this.handleAdd()}
                >
                  新增
                </Button>
              </div>
            ) : null
          }
          <Table
            size="small"
            rowKey={record => record.id}
            dataSource={list ? list : []}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.tableOnChange}
            scroll={{ x: 'max-content'  }}
          />
        </Card>
      </div >
    )
  }

}
export default connect(mapStateToProps)(collectionGroup);